package org.grow.share.controller;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class DownloadAbout {


    @GetMapping("/forTest")
    public ModelAndView testing(){
        System.out.println("got message");
        return new ModelAndView("test");
    }
    @Value("${target}")
    private String targetUrl;
    @GetMapping("/index")
    public ModelAndView index(){

        System.out.println("target : "+targetUrl);
        final Path path = Paths.get(targetUrl);
        if (!Files.exists(path) || !Files.isDirectory(path)){
            throw new RuntimeException("目录文件不存在");
        }
        List<String> files = null;
        try {
            files = Files.list(path)
                    .filter(f -> Files.isRegularFile(f))
                    .map(f -> f.getFileName().toString())
                    .sorted(Comparator.naturalOrder())
                    .collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(files);
        ModelAndView index = new ModelAndView("index");
        index.addObject("files",files);
        return index;
    }


    @GetMapping("/listFiles")
    @ResponseBody
    public Map<String,Object> listFiles(){

        System.out.println("target : "+targetUrl);
        final Path path = Paths.get(targetUrl);
        if (!Files.exists(path) || !Files.isDirectory(path)){
            throw new RuntimeException("目录文件不存在");
        }
        List<String> files = null;
        try {
            files = Files.list(path)
                    .filter(f -> Files.isRegularFile(f))
                    .map(f -> f.getFileName().toString())
                    .sorted(Comparator.naturalOrder())
                    .collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(files);

        HashMap<String, Object> map = new HashMap<>();
        map.put("files",files);
        return map;
    }

    @Value("${blockSize}")
    private int blockSize;
    @GetMapping("/download/{file}")
    public void download(@PathVariable("file") String file,
                         HttpServletResponse response){
        final Path toDownload = Paths.get(targetUrl).resolve(file);
        System.out.println("请求资源　"+toDownload);
        if (Files.notExists(toDownload)) throw new RuntimeException("资源不存在");

        response.reset();
        try {
            response.setContentLength((int)Files.size(toDownload));
        } catch (IOException e) {
            e.printStackTrace();
        }
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition","attachment;filename="+toDownload.getFileName());

        try(
                BufferedInputStream in
                         = new BufferedInputStream(Files.newInputStream(toDownload));
                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        ){
                byte[] buffer = new byte[blockSize];
                while (true){
                    int num = in.read(buffer);
                    if (num == -1 ) break;
                    out.write(buffer,0,num);
                }

        }catch(Exception e){
           e.printStackTrace();
            System.out.println("download error with"+toDownload.getFileName());
        }

    }


}
